<?php
/*
 * @Created by: wangchengcheng
 * @Author: wangchengcheng
 * @Date: 2020-01-06 17:13:10
 * @LastEditors  : wangchengcheng
 * @LastEditTime : 2020-01-09 17:52:06
 */

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Artisan;
use Cache;
use Exception;
use Str;
use App\Models\Article;
use App\Models\ArticleTag;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Note;
use App\Models\Config;
use App\Models\FriendshipLink;
use App\Models\GitProject;
use App\Models\Nav;
use App\Models\SocialiteClient;
use App\Models\SocialiteUser;
use App\Models\Tag;

class ComposerServiceProvider extends ServiceProvider
{
    protected const CACHE_EXPIRE = 86400; //One day in second
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //为了防止 git clone 后composer install
        //因为还没运行迁移php artisan package:discover 报错的问题
        //如果表不存在则不再向下执行
        try{
            //获取配置项
            $config = Config::where('id', '>', 100)->pluck('value', 'name');
        }catch(Exception $exception){
            return true;
        }

        /**
         * 如果已经执行了 migrate
         * 当再执行 db:seed的时候上面的try 并不会触发错误
         * 而是缓存了一个空的config
         * 所以此处需要清空缓存并不再向执行
         */
        if($config->isEmpty()){
            Artisan::call('modelCache:clear');

            return true;
        }
        
        //动态替换 /config目录下的配置项
        config($config->toArray());
        //dd($config);

        try{
            $socialiteClients = SocialiteClient::all();
        }catch(Exception $exception){
            return true;
        }

        $socialiteClients->map(function($socialiteClient){
            config([
                'services.' . $socialiteClient->name . '.client_id' => $socialiteClient->client_id,
                'services.' . $socialiteClient->name . '.client_secret' => $socialiteClient->client_secret,
            ]);
        });

        //开源项目数据
        view()->composer(['layouts/home', 'home/index/git'], function($view){
            $gitProject = GitProject::select('name', 'type')->orderBy('sort')->get();
            //分配数据
            $assign = compact('gitProject');
            $view->with($assign);
        });

        //获取各种统计
        view()->composer(['layouts/home', 'admin/index/index'],function($view){
            $articleCount = Article::count('id');
            $commentCount = Comment::count('id');
            $chatCount = Note::count('id');

            /*SocialiteUser model not use @see \Genealabs\LaravelModelCaching\Traits\Cachable */
            $socialiteUserCount = Cache::remember('count:socialiteUser', static::CACHE_EXPIRE, function(){
                return SocialiteUser::count('id');
            });

            //分配数据

            $assign = compact('articleCount', 'commentCount', 'chatCount', 'socialiteUserCount');
            $view->with($assign);
        });

        view()->composer(['layouts/home', 'admin/index/index'], function($view){
            $latestComments = Comment::with(['article', 'socialiteUser'])
                ->when(Str::isTrue(config('wblog.comment_audit')), function($query){
                    return $query->where('is_audited', 1);
                })
                ->whereHas('socialiteUser', function($query){
                    $query->where('is_admin', 0);
                })
                ->has('article')
                ->orderBy('created_at', 'desc')
                ->limit(17)
                ->get()
                ->each(function($comment){
                    $comment->sub_content = strip_tags($comment->content);

                    if(mb_strlen($comment->sub_content) > 10){
                        if(config('app.locale') === 'zh-CN'){
                            $comment->sub_content = Str::substr($comment->sub_content , 0, 40);
                        }else{
                            $comment->sub_content = Str::words($comment->sub_content, 10, '');
                        }
                    }

                    if(config('app.locale') === 'zh-CN'){
                        $comment->article->sub_title = Str::substr($comment->article->title, 0, 20);
                    }else{
                        $comment->article->sub_title = Str::words($comment->article->title, 5, '');
                    }

                    return $comment;
                });

            $assign = compact('latestComments');
            $view->with($assign);
        });

        view()->composer(['admin/config/*'], function($view) use ($config){
            $assign = compact('config');
            $view->with($assign);
        });

        //分配前台
        view()->composer('layouts/home', function($view) use ($socialiteClients){
            $category = Category::select('id','id', 'name', 'slug')->orderBy('sort')->get();
            $tag = Tag::has('articles')->withCount('articles')->get();
            
            $topArticle = Article::select('id', 'title', 'slug')
                ->where('is_top', 1)
                ->orderBy('created_at', 'desc')
                ->get();
            
            $friendshipLink = FriendshipLink::select('name', 'url')
                ->orderBy('sort')
                ->get();
                
            $nav = Nav::select('name', 'url')
                ->orderBy('sort')
                ->get();
                
            //获取赞赏捐款文章
            $qunArticleId = config('wblog.qq_qun.article_id');
            if(empty($qunArticleId)){
                $qqQunArticle = [];
            }else{
                $qqQunArticle = Article::select('id', 'title')->where('id', $qunArticleId)->first();
            }

            $socialiteClients = $socialiteClients->filter(function($socialiteClient){
                return !empty($socialiteClient->client_id) && !empty($socialiteClient->client_secret);
            });

            $homeFootColNumber = array_filter(config('wblog.social_links')) === [] ? 4 : 3;

            //分配数据
            $assign = compact('category', 'tag', 'topArticle', 'friendshipLink', 'nav', 'qqQunArticle', 
            'socialiteClients', 'homeFootColNumber');

            $view->with($assign);
        });
    }
}
